package com.example.mycityapp;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;

import com.example.mycityapp.JSONParser;
import com.example.mycityapp.util.GPSTracker;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

import com.example.mycityapp.util.Constants;



public class MapActivity extends FragmentActivity{
	
	public String client = "&client_id="+Constants.INSTAGRAM_CLIENT_ID;

	private GoogleMap map;
	private ArrayList<String> nameList = new ArrayList<String>();
	private HashMap<Marker, JSONObject> markerHash = new HashMap<Marker,JSONObject>(); 
	private ArrayList<String> latitudeList = new ArrayList<String>();
	private ArrayList<String> longitudeList = new ArrayList<String>();

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);
//		TextView warningtext=(TextView)findViewById(R.id.warningText);
		try {
			//Putting user on map
			LatLng myLatLng=findMyLatLng(); 
			map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
					.getMap();
			Marker marksMe = map.addMarker(new MarkerOptions().position(myLatLng)
					.title("It is you!"));
			map.moveCamera(CameraUpdateFactory.newLatLngZoom(myLatLng, 15));
			map.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);

			//Necessary for calling getContent
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy);

			String response=JSONParser.getJSONFromUrl("https://api.instagram.com/v1/locations/search?"+createLatLngParam(myLatLng)+client);
			addMarksOnMap(response);
			map.setOnInfoWindowClickListener(
					new OnInfoWindowClickListener(){
						public void onInfoWindowClick(Marker marker){
							JSONObject location = markerHash.get(marker);
							try {
								NewPostPage.locationId = location.getInt("id");
								NewPostPage.locationName = location.getString("name");
								NewPostPage.locationText.setText("Location: "+location.getString("name"));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

							MapActivity.this.finish();
						}
					}
					);

		} catch (JSONException e) {
//			warningtext.setText("Unable to find your location!");
		}
		catch (Exception e) {
	//		warningtext.setText("Unable to find your location!");
		}
	}

	private LatLng findMyLatLng() throws Exception{
		GPSTracker mGPS = new GPSTracker(this);
		double mLong;
		double mLat;
		if(mGPS.canGetLocation ){

			mLat=mGPS.getLatitude();
			mLong=mGPS.getLongitude();

		}else{
			throw new Exception();
		}
		return new LatLng(mLat, mLong);
	}

	private String createLatLngParam(LatLng latlng){
		return "lat="+latlng.latitude+"&lng="+latlng.longitude;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}


	private void addMarksOnMap(String jsonResponse) throws JSONException{
		JSONObject json = new JSONObject(jsonResponse);
		JSONArray jarray = json.getJSONArray("data");

		//TODO:at most 12 markers in order to test, change it later
		for (int i = 0; i < Math.min(12, jarray.length()); ++i) {
			JSONObject location= jarray.getJSONObject(i);
			nameList.add(location.getString("name"));
			latitudeList.add(location.getString("latitude"));
			longitudeList.add(location.getString("longitude"));
			LatLng vendor=new LatLng(Double.parseDouble(latitudeList.get(i)), Double.parseDouble(longitudeList.get(i)));
			Marker marksVendor;
				marksVendor = map.addMarker(new MarkerOptions()
				.position(vendor)
				.title(nameList.get(i))
				.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.azure_marker)));
			markerHash.put(marksVendor, location);
		}

	}

	 
}
